// 基地址
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

// axios.get('/api/getbooks').then(({ data: res }) => {
//   console.log(res)
// })

const tb = document.querySelector('#tb')
const form = document.querySelector('#bookForm')
const filterAdd = document.querySelector('#filterAdd')
// console.log(filterAdd)
// 渲染封装函数
const renderBooks = function (params) {
  axios.get('/api/getbooks', { params }).then(({ data: res }) => {
    // console.log(res)
    const { data } = res
    const html = data
      .map((item) => {
        // console.log(item)
        return `
      <tr>
          <td>${item.id}</td>
          <td>${item.bookname}</td>
          <td>${item.author}</td>
          <td>${item.publisher}</td>
          <td><a href="#" data-id="${item.id}">删除</a></td>
      </tr>
      `
      })
      .join('')
    tb.innerHTML = html
  })
  filterAdd.addEventListener('click', function () {
    // console.log(1)

    const params = serialize(form, { hash: true })
    // console.log(data)
    // const params = data
    renderBooks(params)
  })
}
renderBooks()

// 添加图书
form.addEventListener('submit', function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true })
  // console.log(data)//{bookname: '三毛', author: '222', publisher: '上海图书出版社'}
  axios.post('/api/addbook', data).then(({ data: res }) => {
    // console.log(res)
    alert(res.msg)
    if (res.status !== 201) return

    form.reset()
    renderBooks()
  })
})

// 删除

tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    // console.log(1)
    const id = e.target.dataset.id
    // console.log(id)
    axios.get('/api/delbook?id=' + id).then(({ data: res }) => {
      // console.log(res)
      renderBooks()
    })
  }
})
